<template>
  <div class="login-container">
    <div class="login-wrapper">
      <div class="login-left">
        <div class="login-bg">
          <h1>管理系教职工信息填报系统</h1>
          <p>一站式管理您的教学、科研、学术活动等信息</p>
        </div>
      </div>

      <div class="login-right">
        <div class="login-form">
          <div class="login-header">
            <h2>用户登录</h2>
            <p>请选择身份并登录系统</p>
          </div>

          <el-form
              ref="loginFormRef"
              :model="loginForm"
              :rules="rules"
              size="large"
          >
            <!-- 移除身份选择，后端根据账号返回 roles 自动识别 -->

            <el-form-item prop="username">
              <el-input
                  v-model="loginForm.username"
                  placeholder="请输入用户名"
                  :prefix-icon="User"
              />
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                  v-model="loginForm.password"
                  type="password"
                  placeholder="请输入密码"
                  :prefix-icon="Lock"
                  @keyup.enter="handleLogin"
                  show-password
              />
            </el-form-item>

            <el-form-item>
              <el-button
                  type="primary"
                  size="large"
                  style="width: 100%"
                  :loading="loading"
                  @click="handleLogin"
              >
                {{ loading ? '登录中...' : '登录' }}
              </el-button>
            </el-form-item>
          </el-form>

          <div class="login-tips">
            <el-divider>测试账号</el-divider>
            <div class="tip-item">
              <el-tag type="success" size="small">教职工</el-tag>
              <span>用户名: staff 密码: 123456</span>
            </div>
            <div class="tip-item">
              <el-tag type="warning" size="small">管理员</el-tag>
              <span>用户名: admin 密码: 123456</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Setting } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'  // ✅ 修改这里

const router = useRouter()
const userStore = useUserStore()  // ✅ 修改这里

const loginFormRef = ref()
const loading = ref(false)

const loginForm = reactive({
  username: '',
  password: ''
})

const rules = {
  // 身份由后端 roles 决定
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

// 角色切换时自动填充账号
// 移除身份选择逻辑

const handleLogin = async () => {
  try {
    const valid = await loginFormRef.value.validate().catch(() => false)
    if (!valid) return

    loading.value = true

    // 调用登录方法
    await userStore.login({
      username: loginForm.username,
      password: loginForm.password
    })

    ElMessage.success('登录成功')

    // 根据用户的实际角色跳转（而不是选择的角色）
    if (userStore.isAdmin) {
      router.push('/admin')
    } else {
      router.push('/staff')
    }

  } catch (error) {
    console.error('登录错误:', error)
    ElMessage.error(error.message || '登录失败')
  } finally {
    loading.value = false
  }
}

// 组件挂载时检查是否已登录
onMounted(() => {
  if (userStore.isLoggedIn) {
    const homePath = userStore.isAdmin ? '/admin' : '/staff'
    router.replace(homePath)
  }
})
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-wrapper {
  width: 100%;
  display: flex;
  box-shadow: 0 0 50px rgba(0, 0, 0, 0.1);
}

.login-left {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(45deg, #4facfe 0%, #00f2fe 100%);
  position: relative;
  overflow: hidden;
}

.login-bg {
  text-align: center;
  color: white;
  z-index: 1;
}

.login-bg h1 {
  font-size: 48px;
  font-weight: 300;
  margin-bottom: 20px;
  text-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.login-bg p {
  font-size: 18px;
  opacity: 0.9;
  font-weight: 300;
}

.login-left::before {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="50" cy="50" r="1" fill="white" opacity="0.1"/></pattern></defs><rect width="100%" height="100%" fill="url(%23grain)"/></svg>');
  animation: float 20s ease-in-out infinite;
}

@keyframes float {
  0%, 100% { transform: translate(0, 0) rotate(0deg); }
  33% { transform: translate(30px, -30px) rotate(120deg); }
  66% { transform: translate(-20px, 20px) rotate(240deg); }
}

.login-right {
  width: 480px;
  background: white;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
}

.login-form {
  width: 100%;
  max-width: 380px;
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.login-header h2 {
  font-size: 28px;
  color: #333;
  margin-bottom: 8px;
  font-weight: 400;
}

.login-header p {
  color: #666;
  font-size: 14px;
}

.login-tips {
  margin-top: 30px;
}

.tip-item {
  display: flex;
  align-items: center;
  gap: 12px;
  margin: 8px 0;
  font-size: 13px;
  color: #666;
}

.el-form-item {
  margin-bottom: 24px;
}

.el-button {
  height: 44px;
  border-radius: 6px;
  font-size: 16px;
}

.el-input__wrapper {
  border-radius: 6px;
}

.el-select {
  border-radius: 6px;
}
</style>